from OWRpy import *
import redRi18n
_ = redRi18n.get_(package = 'base')

import signals 
import redRGUI 

class ellipsesComp(OWRpy): 
    globalSettingsList = ['commit']
    def __init__(self, **kwargs):
        OWRpy.__init__(self, **kwargs)
        
        # Python variables
        self.data = {}
        self.RFunctionParam_x = ''
        self.dataClass = ''
        
        # Inputs
        self.inputs.addInput('id0', 'variables', signals.base.RMatrix, self.processdata)#, multiple = True)
        
        # Outputs
        self.outputs.addOutput("ellipses Output",_("ellipses Output"), signals.plotting.RPlotAttribute)
        
        # GUI
        self.RFunctionParam_groupScale = redRGUI.base.groupBox(self.controlArea, label="Scaling options")
        
        self.RFunctionParam_selectScale = redRGUI.base.radioButtons(self.RFunctionParam_groupScale,  label = "Scale", 
        buttons = [('Chi-square'), ('Custom')],
        setChecked='Chi-square',orientation='horizontal', callback = self.onTestChange)
        
        self.RFunctionParam_chisq = redRGUI.base.groupBox(self.RFunctionParam_groupScale, label="Chi-squared")
        self.RFunctionParam_custom = redRGUI.base.groupBox(self.RFunctionParam_groupScale, label="Custom")
        self.RFunctionParam_custom.hide()
        
        ## chi-squared
        self.RFunctionParam_selectConfRange = redRGUI.base.radioButtons(self.RFunctionParam_chisq,  label = "Confidence region", 
        buttons = [('About observations'), ('About mean')],
        setChecked='About observations',orientation='horizontal')
        self.RFunctionParam_rconfInt = redRGUI.base.lineEdit(self.RFunctionParam_chisq, label = "Confidence region scaling of half-diameters", text = '0.95', callback = self.onTestChange)

        ## custom
        self.RFunctionParam_rscale = redRGUI.base.lineEdit(self.RFunctionParam_custom, label = "Custom scaling of half-diameters", text = '1', callback = self.onTestChange)
        
        ## Plot attributes
        self.RFunctionParam_lty = redRGUI.base.comboBox(self.controlArea, label = 'Line types', displayLabel=True,
        items = [(1,'________'), (2,'- - - -'), (3,'........'), (4,'_._._._.'), (5,'__ __ __'), (6,'__.__.__.')])
        self.RFunctionParam_ecol = redRGUI.base.comboBox(self.controlArea, label = 'Line color', displayLabel=True,
        items = [(1,'Black'), (2,'Red'), (3,'Green'), (4,'Blue'), (5,'Cyan'), (6,'Magenta'), (7,'Yellow'), (8,'Gray')])
        self.RFunctionParam_esteps = redRGUI.base.spinBox(self.controlArea, label = "Steps:", min = 5,max=500, value = 72 )
        
        
        self.commit = redRGUI.base.commitButton(self.bottomAreaRight, _("Commit"), alignment=Qt.AlignLeft, 
        callback = self.commitFunction, processOnInput=True)

    def onTestChange(self):
        print self.RFunctionParam_selectScale.getChecked()
        if self.RFunctionParam_selectScale.getChecked() == 'Chi-square' :
            self.RFunctionParam_custom.hide()
            self.RFunctionParam_chisq.show()
        elif self.RFunctionParam_selectScale.getChecked() == 'Custom' :
            self.RFunctionParam_custom.show()
            self.RFunctionParam_chisq.hide()
        
        
    def processdata(self, data):
        if not self.require_librarys(["graphics"]):
            self.status.setText('R Libraries Not Loaded.')
            return
        if data:
            self.RFunctionParam_x=data.getData()
            #self.data = data
            self.commitFunction()
            self.dataClass=self.R('class('+self.RFunctionParam_x+')')
            if self.dataClass not in ['rplus', 'aplus', 'rcomp', 'acomp'] :
                self.status.setText('The class of the input is not compositional. Please parse data though widget "Close the simplex".')
                return
        else:
            self.RFunctionParam_x=''
        
    def commitFunction(self):
        if str(self.RFunctionParam_x) == '': 
            self.status.setText('No data')
            return
        
        self.degFreedom = self.R('ncol('+str(self.RFunctionParam_x)+')')-1
        
        injection = []
        if unicode(self.RFunctionParam_selectScale.getChecked()) == 'Custom':
            if unicode(self.RFunctionParam_rscale.text()) != '':
                string = 'r='+unicode(self.RFunctionParam_rscale.text())+''
                injection.append(string)
            else:
                self.status.setText('Enter custom scaling of half-diameters.')
                return      
        elif unicode(self.RFunctionParam_selectScale.getChecked()) == 'Chi-square':
            if unicode(self.RFunctionParam_rconfInt.text()) != '':
                if unicode(self.RFunctionParam_selectConfRange.getChecked()) == 'About observations':
                    string = 'r=sqrt(qchisq(p='+unicode(self.RFunctionParam_rconfInt.text())+',df='+str(self.degFreedom)+'))'
                elif unicode(self.RFunctionParam_selectConfRange.getChecked()) == 'About mean':
                    string = 'r=sqrt(qchisq(p='+unicode(self.RFunctionParam_rconfInt.text())+',df='+str(self.degFreedom)+')/nrow('+unicode(self.RFunctionParam_x)+'))'
                injection.append(string)
            else:
                self.status.setText('Enter 1-alpha.')
                return    
        
        if unicode(self.RFunctionParam_lty.currentId()) != '':
            string = 'lty='+unicode(self.RFunctionParam_lty.currentId())+''
            injection.append(string)
        if unicode(self.RFunctionParam_ecol.currentId()) != '':
            string = 'col='+unicode(self.RFunctionParam_ecol.currentId())+''
            injection.append(string)
        if unicode(self.RFunctionParam_esteps.text()) != '':
            string = 'steps='+unicode(self.RFunctionParam_esteps.value())+''
            injection.append(string)

        inj = ','.join(injection)
        
        newPlotAtt = signals.plotting.RPlotAttribute(self, data = 'ellipses(mean(%s), var(%s), %s)' % (str(self.RFunctionParam_x), str(self.RFunctionParam_x), inj))
        print '!Output', newPlotAtt
        self.rSend("ellipses Output", newPlotAtt)